package pt.compflow.client;

import java.io.IOException;
import java.io.InputStream;

import org.restlet.Request;
import org.restlet.Response;
import org.restlet.Restlet;
import org.restlet.data.MediaType;
import org.restlet.data.Status;
import org.restlet.representation.InputRepresentation;
import org.restlet.representation.Representation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.hp.hpl.jena.shared.NotFoundException;

public class ClientRestlet extends Restlet {
	
	private static final Logger LOG = LoggerFactory.getLogger(ClientRestlet.class);
	
	@Override
	public void handle(Request request, Response response) {
		//final String rootPath = System.getProperty("user.dir") + "\\client\\";
		String type = request.getMethod().getName();
		String fileName = (String) request.getResourceRef().getIdentifier();
		fileName = fileName.substring(request.getHostRef().getHostIdentifier().length() + 1);

		if(fileName.endsWith("favicon.ico")) {
			response.setStatus(Status.CLIENT_ERROR_NOT_FOUND);
			return;
		}
		
		if (type.equalsIgnoreCase("get")) {
			
			try {
				Representation r = readStaticFile(fileName);
				response.setEntity(r);
			} catch (NotFoundException e) {
				LOG.error("File " + fileName + " not found! Error 404!");
				response.setStatus(new Status(Status.CLIENT_ERROR_NOT_FOUND, e.getMessage()));
			} catch (IOException e) {
				LOG.error("Exception reading " + fileName + "!", e);
				response.setStatus(new Status(Status.SERVER_ERROR_INTERNAL, e.getMessage()));
			}
		}
	}
	
	public static Representation readStaticFile(String fileName) throws NotFoundException, IOException {
	    MediaType type = MediaType.TEXT_HTML;
	    
	    if(fileName.endsWith(".js"))
	    	type = MediaType.TEXT_JAVASCRIPT;
	    else if(fileName.endsWith(".css"))
	    	type = MediaType.TEXT_CSS;
	    else if(fileName.endsWith(".pdf"))
	    	type = MediaType.APPLICATION_PDF;
	    
	    LOG.debug(fileName);
		
		InputStream is = ClientRestlet.class.getResourceAsStream("/" + fileName);
	    Representation representation = new InputRepresentation(is, type);
	    return representation;
	}
}
